package zjw.springboot.test.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2020-05-20.
 */
@RequestMapping("/excel")
@Controller
@Slf4j
public class ExcelController {

    @GetMapping("/index")
    public String index() {
        String classPath = this.getClass().getClassLoader().getResource("").getPath();
        System.out.println(classPath);
        if (classPath.endsWith("target/classes/")) {
            // 开发环境下会定位到class目录造成应用自动重启
            classPath = classPath + "../";
        }
        System.out.println(classPath);
        return "index";
    }

    @GetMapping("/export")
    public void exportExcel(HttpServletResponse response) {
        try {
            List<ExcelModel> list = new ArrayList<>();
            for (int i = 0; i < 10; i++) {
                ExcelModel item = new ExcelModel();
                item.setName("伟哥" + i);
                item.setAge(i);
                list.add(item);
            }
            OutputStream os = response.getOutputStream();
            //重置输出流
            response.reset();
            response.setContentType("application/vnd.ms-excel");
            //设置响应标题>这里浏览器会提示用户选择下载文件需要存放的路径>
            response.setHeader("Content-disposition", "attachment; fileName=" + new String(("伟哥" + ".xlsx").getBytes(), "iso8859-1"));
            EasyExcel.write(os, ExcelModel.class).sheet("伟哥").doWrite(list);
        } catch (Exception e) {
            log.error("method: exportExcel Exception {}", e);
        }
    }

    @Data
    public static class ExcelModel implements Serializable {
        private static final long serialVersionUID = -7025817529166094159L;

        @ExcelProperty("姓名")
        private String name;
        @ExcelProperty("年龄")
        private Integer age;

    }

    public Object instance = null;

    private static final int _1MB = 1024 * 1024;

    private byte[] bigSize = new byte[2 * _1MB];


    public static void main(String[] args) throws InterruptedException {
        ExcelController objA = new ExcelController();
        ExcelController objB = new ExcelController();
        objA.instance = objB;
        objB.instance = objA;

        System.gc();//System.gc() 只是建议gc，不一定执行

    }
}
